<template>
  <div class="order-management">
    <PageLayout>


      <template #search>

      </template>

      <!-- 表格头部 -->
      <template #header>
        <div class="compact-table-header">


          <n-button type="info" @click="handleRefresh" class="compact-add-btn" size="large">
            <template #icon>
              <n-icon>
                <RefreshOutline />
              </n-icon>
            </template>
            刷新数据
          </n-button>

          <n-button type="info" @click="handleUploadImage" class="compact-add-btn" size="large">
            <template #icon>
              <n-icon>
                <CloudUpload />
              </n-icon>
            </template>
            上传图片
          </n-button>
        </div>
      </template>

      <!-- 表格内容 -->
      <template #table>
        <n-data-table :columns="columns" :data="tableData" :loading="loading" :single-line="false" :scroll-x="2000"
          :flex-height="true" class="data-table" striped :row-key="(row) => row.orderId"
          :checked-row-keys="checkedRowKeys" @update:checked-row-keys="handleCheckedRowKeysChange"
          :row-class-name="getRowClassName" @row-click="handleRowClick" />
      </template>

      <!-- 分页 -->
      <template #pagination>
        <n-pagination v-model:page="pagination.page" v-model:page-size="pagination.pageSize"
          :item-count="pagination.itemCount" :page-sizes="[10, 20, 50, 100, 200]" show-size-picker show-quick-jumper
          :prefix="paginationPrefix" @update:page="handlePageChange" @update:page-size="handlePageSizeChange" />
      </template>
    </PageLayout>














    <!-- 上传图片 -->
    <n-modal v-model:show="showOrderModal" preset="card" title="图片上传" class="modern-modal" :style="{ width: '800px' }"
      :auto-focus="false" :close-on-esc="false" transform-origin="center">



      <template #default>
        <div class="modal-content">
          <div class="form-grid">

            <div class="form-section">
              <h4 class="section-title">图片信息</h4>
              <n-upload ref="registerAvatorUploadRef" list-type="image-card" :max="1" :custom-request="handleUpload"
                @remove="handleRemove" :file-list="avatarFiles" @change="handleFileChange">
                <n-upload-dragger>
                  <div class="upload-tips">
                    <n-icon size="24" depth="3">
                      <EyeOutline />
                    </n-icon><br />
                    <n-text depth="3" style="font-size: 10px;color: red;">点击或拖拽</n-text><br />
                    <n-p depth="3" style="margin: 0 0; font-size: 10px;color: red;">勿传敏感信息</n-p>
                  </div>
                </n-upload-dragger>

                <template #file="{ file }">
                  <n-image :src="file.url" :alt="file.name" width="100" height="100" object-fit="cover"
                    preview-disabled>
                    <template #placeholder>
                      <n-spin size="small" />
                    </template>
                  </n-image>
                </template>
              </n-upload>
            </div>

          </div>
        </div>
      </template>


      <template #action>
        <div class="modal-actions">
          <n-space v-if="modalMode !== 'view'" size="medium">
            <!-- <n-button @click="cancelOrderModal" class="cancel-btn">取消</n-button> -->
            <n-button type="primary" @click="confirmOrderModal('add')" :loading="submitLoading" class="confirm-btn">
              <template #icon>
                <n-icon>
                  <AddOutline />
                </n-icon>
              </template>
              确认上传
            </n-button>
          </n-space>
        </div>
      </template>
    </n-modal>


  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, h } from 'vue'
import { useMessage, useDialog, FormInst, FormRules, InputInst, useNotification, UploadFileInfo } from 'naive-ui'
import { NButton, NTag, NImage, NSwitch, zhCN, dateZhCN } from 'naive-ui'
import {
  SearchOutline,
  RefreshOutline,
  AddOutline,
  DownloadOutline,
  CreateOutline,
  TrashOutline,
  EyeOutline,
  CloudUpload
} from '@vicons/ionicons5'
import PageLayout from '@/components/PageLayout.vue'
import { v4 as uuidv4 } from 'uuid';

import { userAPI } from '@/api/user'
import { imageAPI } from '@/api/image'
import { request } from '@/utils/request'


// 添加组件名称
defineOptions({
  name: 'ProductManagement'
})

const message = useMessage()
const dialog = useDialog()
const loading = ref(false)

// 行选中相关
const checkedRowKeys = ref<string[]>([])
const selectedRows = ref<any[]>([])

// 头像
const registerAvatorUploadRef = ref(null) // 头像上传

// 处理行选中变化
const handleCheckedRowKeysChange = (keys: string[]) => {
  checkedRowKeys.value = keys
  selectedRows.value = tableData.value.filter(item => keys.includes(item.orderId))
}

// 获取行类名
const getRowClassName = (row: any) => {
  if (checkedRowKeys.value.includes(row.orderId)) {
    return 'rainbow-selected-row'
  }
  return ''
}




// 处理行点击事件
const handleRowClick = (row: any, index: number) => {
  const rowKey = row.orderId
  const currentIndex = checkedRowKeys.value.indexOf(rowKey)

  if (currentIndex > -1) {
    // 如果当前行已选中，则取消选中
    checkedRowKeys.value.splice(currentIndex, 1)
  } else {
    // 如果当前行未选中，则选中
    checkedRowKeys.value.push(rowKey)
  }

  // 更新选中的行数据
  selectedRows.value = tableData.value.filter(item => checkedRowKeys.value.includes(item.orderId))

  // 打印日志方便调试
  console.log('点击行:', row.orderId, '当前选中:', checkedRowKeys.value)
}


// 弹窗相关
const showOrderModal = ref(false) // 新增弹窗
const showViewModal = ref(false) // 查看弹窗
const showEditModal = ref(false) // 编辑弹窗

const modalMode = ref<'add' | 'edit' | 'view'>('add')
const modalTitle = computed(() => {
  const titles = {
    add: '新增用户',
    edit: '编辑用户信息',
    view: '查看用户信息'
  }
  return titles[modalMode.value]
})
const submitLoading = ref(false)
const editrFormRef = ref<FormInst | null>(null)
const addProductFormRef = ref<FormInst | null>(null)


// 订单表单
const orderForm = ref({
  id: '',// 唯一的32位的
  uname: '',// 用户名
  avatarUrl: '',// 头像minio链接
  acrossNum: '',// 密码
  encryptPwd: '',// 加密后的密码
  encryptionAlgorithm: '',// 加密算法
  email: '',// 电子邮件
  telNum: '',// 电话号码
  wechatAbt: '',// 微信相关信息
  roleNum: '',// 角色编号
  freezeOrnnt: '',// 是否冻结 0 不冻结 1 冻结
  createTm: '',// 创建时间 timestamp格式
  updateTm: '',// 最新修改时间timestamp格式
  accountMoney: 0.00,// 账户金额
  bAccount: 0.0000,// 账户金额
})


const imageValidationRules = {
  // 允许的图片格式（根据业务需求调整）
  allowedTypes: ['image/jpeg', 'image/png', 'image/webp', 'image/gif'],
  allowedExtensions: ['jpg', 'jpeg', 'png', 'webp', 'gif'], // 用于后缀名校验
  maxSize: 10 * 1024 * 1024, // 最大5MB（单位：字节）
  maxCount: 1 // 最大上传数量（你的代码中已限制为1）
};

// 错误提示信息
const imageErrorMessages = {
  typeError: `请上传以下格式的图片：${imageValidationRules.allowedExtensions.join('、')}`,
  sizeError: `图片大小不能超过${imageValidationRules.maxSize / 1024 / 1024}MB`,
  countError: `最多只能上传${imageValidationRules.maxCount}张图片`,
  requiredError: '请上传商品图片' // 如果图片为必填项
};



// 搜索表单
const searchForm = ref({
  id: '',// 唯一的32位的
  uname: '',// 用户名
  avatarUrl: '',// 头像minio链接
  acrossNum: '',// 密码
  encryptPwd: '',// 加密后的密码
  encryptionAlgorithm: '',// 加密算法
  email: '',// 电子邮件
  telNum: '',// 电话号码
  wechatAbt: '',// 微信相关信息
  roleNum: '',// 角色编号
  freezeOrnnt: '',// 是否冻结 0 不冻结 1 冻结
  createTm: '',// 创建时间 timestamp格式
  updateTm: '',// 最新修改时间timestamp格式
  accountMoney: 0.00,// 账户金额
  bAccount: 0.0000,// 账户金额
})


// 分页配置
const pagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0
})

const UUID = () => {
  return uuidv4().replace(/-/g, '').substring(0, 32)
}



// ======================= 上传头像 =======================
const isUploadAvatarDone = ref(false); //头像是否上传成功
const avatarFiles = ref<UploadFileInfo[]>([]);
const showloading = ref(false);

// 文件状态变化处理
const handleFileChange = (options: { file: UploadFileInfo, fileList: UploadFileInfo[] }) => {
  avatarFiles.value = options.fileList;
};

// 独立生成器函数
function generateUniqueName(ext: string, username: string) {
  const timestamp = (Date.now() - new Date('2024-01-01').getTime())
    .toString(36)
    .toUpperCase();
  const randomPart = Math.random().toString(36).slice(2, 6);
  // return `${timestamp}_${randomPart}.${ext}`;
  return `${username}.${ext}`;
}

// 上传处理
const handleUpload = async (options: { file: UploadFileInfo }) => {
  try {
    if (!options?.file || !(options.file.file instanceof File)) {
      throw new Error('未选择有效文件');
    }
    const file = options.file.file as File;
    // 2. 校验文件类型（MIME类型）
    if (!imageValidationRules.allowedTypes.includes(file.type)) {
      message.error(imageErrorMessages.typeError);
      // 清空无效文件
      avatarFiles.value = [];
      return;
    }

    // 3. 校验文件大小
    if (file.size > imageValidationRules.maxSize) {
      message.error(imageErrorMessages.sizeError);
      avatarFiles.value = [];
      return;
    }

    // 4. 校验文件数量（你的代码中已通过max=1限制，这里做二次确认）
    if (avatarFiles.value.length > imageValidationRules.maxCount) {
      message.error(imageErrorMessages.countError);
      return;
    }

    // 5. 校验文件后缀名（双重保险，防止MIME类型伪造）
    const fileExtension1 = file.name.split('.').pop()?.toLowerCase();
    if (!fileExtension1 || !imageValidationRules.allowedExtensions.includes(fileExtension1)) {
      message.error(imageErrorMessages.typeError);
      avatarFiles.value = [];
      return;
    }

    // 校验文件后缀
    const initialValues = ['bmp', 'jpg', 'png', 'tif', 'gif', 'pcx', 'tga', 'exif', 'fpx', 'svg', 'psd',
      'cdr', 'pcd', 'dxf', 'ufo', 'eps', 'ai', 'raw', 'WMF', 'webp', 'avif', 'apng'];
    const safeAvatarFilename = ref(new Set(initialValues));
    const lastDotIndex = options.file.name.lastIndexOf('.');
    const fileSuffix = (lastDotIndex > 0) ? options.file.name.substring(lastDotIndex + 1) : '';
    if (!safeAvatarFilename.value.has(fileSuffix)) {
      message.error("请上传安全的头像文件!");
      avatarFiles.value = [];
      return;
    }

    // 文件名生成逻辑 --------------------------------------------------------
    const originalFile = options.file.file as File;
    const fileExtension = originalFile.name.split('.').pop() || 'png';
    // 将用户名作为头像文件名（用户名不重复的）
    const sanitizedName = generateUniqueName(fileExtension, UUID());
    // 创建新文件对象
    const modifiedFile = new File([originalFile], sanitizedName, { type: originalFile.type });
    // 更新上传文件引用
    options.file.file = modifiedFile;
    options.file.name = sanitizedName;
    // ------------------------------------------------------------------------
    const formData = new FormData();
    formData.append('avatar', options.file.file as File);
    formData.append('userId', UUID());

    // 显示上传进度
    options.file.status = 'uploading';
    options.file.percentage = 10;
    showloading.value = true
    const res = await request.upload<{ url: string }>(
      "/api/uploadImage",
      options.file.file,
      { userId: UUID() }, // 可添加额外参数
      { headers: { 'X-Upload-Type': 'avatar' } },
      { fieldName: 'avatar' } // 和后端 @RequestParam 名称保持一致
    );
    console.log("商品图片上传", res)
    if (res.code === 200) {
      message.success("商品图片上传成功!");
      options.file.status = 'finished';
      // @ts-ignore
      options.file.url = res.data; // 显示缩略图
      // @ts-ignore
      orderForm.value.productImgUrl = res.data
      isUploadAvatarDone.value = true;
      showloading.value = false
    }

  } catch (error) {
    options.file.status = 'error';
    message.error(`商品图片上传失败: ${(error as Error).message}`);
  }
};

// 删除处理（完整版）
const handleRemove = async (options: { file: UploadFileInfo }) => {

  try {
    // console.log(options.file.name)
    const res = await imageAPI.deleteImage({ bucketName: 'banners', fileName: options.file.name })
    if (res.code === 200 && res.msg === '图片删除成功') {
      message.success('图片已删除');
    } else {
      message.error('图片删除失败，请联系管理员');
    }

  } catch (error) {
    message.error(`图片失败: ${(error as Error).message}`);
  }
};
// ======================= 上传头像 =======================




// 分页前缀
const paginationPrefix = ({ itemCount }: any) => `共 ${itemCount} 条数据`

// 表格列配置
const columns: any[] = [
  {
    title: '商品图片',
    key: 'fileName',
    width: 10,
    render: (row: any) => {
      if (row.fileName) {
        return h(NImage, {
          width: 60,
          height: 60,
          src: 'https://julong666.com:9001/' + row.bucketName + '/' + row.fileName,
          objectFit: 'cover',
          previewDisabled: false,
          style: 'border-radius: 6px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);'
        })
      }
    }
  },
  {
    title: '唯一标识',
    key: 'etag  ',
    width: 50,
    ellipsis: {
      tooltip: true
    },
    render: (row: any) => h('span', null, row.etag || '')
  },
  {
    title: '文件名',
    key: 'fileName  ',
    width: 50,
    ellipsis: {
      tooltip: true
    },
    render: (row: any) => h('span', null, row.fileName || '')
  },
  {
    title: '地址',
    key: 'bucketName  ',
    width: 30,
    ellipsis: {
      tooltip: true
    },
    render: (row: any) => h('span', null, row.bucketName || '未知地址')
  },
  {
    title: '后缀',
    key: 'contentType  ',
    width: 20,
    ellipsis: {
      tooltip: true
    },
    render: (row: any) => h('span', null, row.contentType || '无后缀')
  },

  {
    title: '大小',
    key: 'fileSize  ',
    width: 15,
    ellipsis: {
      tooltip: true
    },
    render: (row: any) => h('span', null, row.fileSize || '')
  },
  {
    title: '上传时间',
    key: 'lastModified',
    width: 15,
    render: (row: any) => {
      if (!row.lastModified) {
        return h('div', { class: 'time-cell' }, [
          h('div', { class: 'time-date' }, '未知日期'),
          h('div', { class: 'time-time' }, '未知时间')
        ])
      }

      const date = new Date(row.lastModified)
      const dateStr = date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      })
      const timeStr = date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })

      return h('div', { class: 'time-cell' }, [
        h('div', { class: 'time-date' }, dateStr),
        h('div', { class: 'time-time' }, timeStr)
      ])
    },
    sorter: (row1: any, row2: any) => {
      const time1 = row1.lastModified ? new Date(row1.lastModified).getTime() : 0
      const time2 = row2.lastModified ? new Date(row2.lastModified).getTime() : 0
      return time1 - time2
    }
  },
  // 操作按钮 - 右侧固定
  {
    title: '操作',
    key: 'actions',
    width: 20,
    align: 'center',
    fixed: 'right',
    render: (row: any) => {
      const buttons = []
      if (true) {
        buttons.push(h(NButton, {
          size: 'small',
          type: 'error',
          quaternary: true,
          style: { marginLeft: '8px' },
          onClick: () => handleDelete(row)
        }, { default: () => '删除' }))
      }
      return h('div', { class: 'action-buttons' }, buttons)
    }
  }
]

// 表格数据
const tableData = ref<any[]>([])
const allData = ref<any[]>([])

// 获取列表信息
const getOrderList = async (params: any) => {
  try {
    loading.value = true
    try {

      const res = await imageAPI.getImageList({ bucketName: 'banners', pageSize: pagination.value.pageSize, currentPage: pagination.value.page })

      const listCount = await imageAPI.getImageListCount({ bucketName: 'banners', pageSize: pagination.value.pageSize, currentPage: pagination.value.page })

      if (res.code === 200) {
        // 处理新的响应格式
        if (res.data && typeof res.data === 'object') {
          // 如果是 OrderListResponse 格式
          if ('list' in res.data) {
            tableData.value = res.data.list || []
            allData.value = res.data.list || []
            pagination.value.itemCount = listCount.data || 0
          } else if (Array.isArray(res.data)) {
            // 如果直接是数组格式
            tableData.value = res.data
            allData.value = res.data
            pagination.value.itemCount = listCount.data
          } else {
            // 其他格式
            tableData.value = []
            allData.value = []
            pagination.value.itemCount = 0
          }
        } else {
          tableData.value = []
          allData.value = []
          pagination.value.itemCount = 0
        }

        console.log("tableData.value", tableData.value)
      } else {
        console.error('❌ API返回错误:', res)
        message.error(res.msg || res.message || '获取图片列表失败')
        // 清空数据
        tableData.value = []
        allData.value = []
        pagination.value.itemCount = 0
      }

    } catch (apiError: any) {
      console.error('❌ API调用异常:', apiError)
      message.error(`连接后端失败: ${apiError.message || '网络错误'}`)
      // 清空数据
      tableData.value = []
      allData.value = []
      pagination.value.itemCount = 0
    }

  } catch (error: any) {
    console.error('❌ 获取图片失败:', error)
    message.error('获取图片列表失败: ' + (error.message || '网络错误'))
    // 清空数据
    tableData.value = []
    allData.value = []
    pagination.value.itemCount = 0
  } finally {
    loading.value = false
  }
}


const handleRefresh = () => {
  getOrderList(null) // 重新加载数据
  message.info('数据已刷新')
}

// 弹窗相关函数
const resetOrderForm = () => {
  orderForm.value = {
    id: '',// 唯一的32位的
    uname: '',// 用户名
    avatarUrl: '',// 头像minio链接
    acrossNum: '',// 密码
    encryptPwd: '',// 加密后的密码
    encryptionAlgorithm: '',// 加密算法
    email: '',// 电子邮件
    telNum: '',// 电话号码
    wechatAbt: '',// 微信相关信息
    roleNum: '',// 角色编号
    freezeOrnnt: '',// 是否冻结 0 不冻结 1 冻结
    createTm: '',// 创建时间 timestamp格式
    updateTm: '',// 最新修改时间timestamp格式
    accountMoney: 0.00,// 账户金额
    bAccount: 0.0000,// 账户金额
  }
}


const cancelOrderModal = () => {
  // console.log("关闭弹窗")
  // const fileName = orderForm.value.productImgUrl.split('/').pop()
  // console.log("删除文件", fileName)
  // // 调用后端删除接口
  // if (fileName !== '') {
  //   productAPI.deleteProductImg({ productImgUrl: fileName })
  // }
  // isUploadAvatarDone.value = false;
  // avatarFiles.value = [];
  // orderForm.value.productImgUrl = ''
  // showOrderModal.value = false
  // resetOrderForm()
}

const confirmOrderModal = async (type: string) => {
  showOrderModal.value = false
  avatarFiles.value = [];
  handleRefresh()
}



const deleteImage = async (row: any) => {

  try {

    loading.value = true

    const res = await imageAPI.deleteImage(row)
    console.log(res)

    // if (res.code === 200 && res.msg === '商品删除成功') {
    //   getOrderList(null) // 刷新列表
    //   loading.value = false
    //   message.success('商品删除成功！')
    // }



  } catch (error) {
    message.error('图片删除失败,请联系管理员')
    loading.value = false
  } finally {
    loading.value = false
  }
}


const handleUploadImage = () => {
  showOrderModal.value = true;

}


const handleDelete = (row: any) => {
  dialog.warning({
    title: '确认删除',
    content: `确定要删除图片 \n  【${row.fileName}】 吗？\n 删除后图片永久消失无备份！`,
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: () => {
      const index = allData.value.findIndex(item => item.fileName === row.fileName)
      if (index !== -1) {
        allData.value.splice(index, 1)
        pagination.value.itemCount = allData.value.length
        // 重新处理分页显示
        const startIndex = (pagination.value.page - 1) * pagination.value.pageSize
        const endIndex = startIndex + pagination.value.pageSize
        tableData.value = allData.value.slice(startIndex, endIndex)
        loading.value = true // 表格loading

        deleteImage(row) // 调用后台删除商品

        message.success('图片删除成功')
      }
    }
  })
}


const handlePageChange = (page: number) => {
  pagination.value.page = page
  getOrderList(null) // 重新加载数据
}

const handlePageSizeChange = (pageSize: number) => {
  pagination.value.pageSize = pageSize
  pagination.value.page = 1
  getOrderList(null) // 重新加载数据
}

onMounted(() => {
  // 页面加载时获取列表（如果API失败会自动加载模拟数据）
  getOrderList(null)
})


</script>

<style scoped>
/* 头像 */
.upload-tips {
  padding: 12px;
  text-align: center;
}

.page-container {
  padding: var(--spacing-lg);
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--bg-color-secondary);
}

.search-card {
  flex-shrink: 0;
  margin-bottom: var(--spacing-lg);
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-sm);
}

.table-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.table-header-section {
  flex-shrink: 0;
  background: var(--bg-color-primary);
  border: 1px solid var(--border-color-primary);
  border-bottom: none;
  border-radius: 12px 12px 0 0;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color-primary);
}

.table-content {
  flex: 1;
  overflow: hidden;
  border-left: 1px solid var(--border-color-primary);
  border-right: 1px solid var(--border-color-primary);
  background: var(--bg-color-primary);
  min-height: 50%;
  max-height: 100%;
}

.table-data-area {
  flex: 1;
  overflow: auto;
  height: 100%;
  padding-bottom: 0px;
}

/* 🔧 表格基础样式 - 专业级滚动配置 */
.data-table {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

/* 表格包装器 - 核心滚动配置 */
.data-table :deep(.n-data-table-wrapper) {
  border-radius: 8px;
  height: 100%;
}

/* 表格基础容器 */
.data-table :deep(.n-data-table) {
  height: 100%;
  /* 让Naive UI处理所有滚动逻辑 */
}

/* 表头样式 - 确保固定功能正常 */
.data-table :deep(.n-data-table-th) {
  background-color: #fafafa !important;
  font-weight: 600;
  font-size: 14px;
  color: #262626;
  border-bottom: 2px solid #e8e8e8;
  padding: 16px 12px;
  white-space: nowrap;
  position: sticky;
  top: 0;
  z-index: 10;
}

/* 表格单元格样式 */
.data-table :deep(.n-data-table-td) {
  padding: 12px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  font-size: 15px;
  font-weight: 500;
  line-height: 1.6;
  letter-spacing: 0.3px;
  color: #2c3e50;
  border-bottom: 1px solid #f0f0f0;
  vertical-align: top;
  position: relative;
  z-index: 1;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

/* 固定列样式 - 确保固定列正常显示 */
.data-table :deep(.n-data-table-td.n-data-table-td--fixed-left),
.data-table :deep(.n-data-table-td.n-data-table-td--fixed-right) {
  position: sticky !important;
  z-index: 10 !important;
  background: var(--n-td-color) !important;
}

/* 固定列在悬浮时的背景处理 */
.data-table :deep(.n-data-table-tr:hover .n-data-table-td.n-data-table-td--fixed-left),
.data-table :deep(.n-data-table-tr:hover .n-data-table-td.n-data-table-td--fixed-right) {
  background: var(--n-td-color-hover) !important;
  z-index: 10 !important;
}

/* 固定列在选中时的背景处理 */
.data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td.n-data-table-td--fixed-left),
.data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td.n-data-table-td--fixed-right) {
  background: var(--n-td-color-hover) !important;
  z-index: 10 !important;
}

/* 表格行悬停效果 - 动态渐变效果 */
.data-table :deep(.n-data-table-tr) {
  transition: all 0.3s ease;
  position: relative;
  cursor: pointer;
}

.data-table :deep(.n-data-table-tr:hover) {
  background-color: rgba(0, 0, 0, 0.02);
}

.data-table :deep(.n-data-table-tr:hover .n-data-table-td) {
  background: linear-gradient(90deg,
      rgba(255, 0, 0, 0.2) 0%,
      rgba(255, 165, 0, 0.2) 12.5%,
      rgba(255, 255, 0, 0.2) 25%,
      rgba(0, 255, 0, 0.2) 37.5%,
      rgba(0, 255, 255, 0.2) 50%,
      rgba(0, 0, 255, 0.2) 62.5%,
      rgba(75, 0, 130, 0.2) 75%,
      rgba(238, 130, 238, 0.2) 87.5%,
      rgba(255, 0, 0, 0.2) 100%) !important;
  background-size: 400% 100%;
  animation: rainbowMove 4s linear infinite;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 0, 0, 0.1);
  z-index: 0;
}

.data-table :deep(.n-data-table-tr:hover .n-data-table-td)>* {
  position: relative;
  z-index: 2;
}

/* 选中行的彩虹色动态渐变效果 */
.data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td) {
  background: linear-gradient(90deg,
      rgba(255, 0, 0, 0.25) 0%,
      rgba(255, 165, 0, 0.25) 12.5%,
      rgba(255, 255, 0, 0.25) 25%,
      rgba(0, 255, 0, 0.25) 37.5%,
      rgba(0, 255, 255, 0.25) 50%,
      rgba(0, 0, 255, 0.25) 62.5%,
      rgba(75, 0, 130, 0.25) 75%,
      rgba(238, 130, 238, 0.25) 87.5%,
      rgba(255, 0, 0, 0.25) 100%) !important;
  background-size: 400% 100%;
  animation: rainbowMove 4s linear infinite;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 0, 0, 0.2);
  z-index: 0;
}

.data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td)>* {
  position: relative;
  z-index: 2;
}

@keyframes rainbowMove {
  0% {
    background-position: 0% 50%;
  }

  25% {
    background-position: 100% 50%;
  }

  50% {
    background-position: 200% 50%;
  }

  75% {
    background-position: 300% 50%;
  }

  100% {
    background-position: 400% 50%;
  }
}

/* 时间显示样式 */
.time-cell {
  line-height: 1.5;
  font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
}

.time-date {
  font-weight: 600;
  font-size: 14px;
  color: #1a202c;
  margin-bottom: 3px;
  letter-spacing: 0.2px;
}

.time-time {
  font-size: 13px;
  font-weight: 500;
  color: #4a5568;
  letter-spacing: 0.3px;
}

/* 深色模式时间显示样式 */
html.dark .time-date {
  color: #e2e8f0 !important;
}

html.dark .time-time {
  color: #a0aec0 !important;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.action-buttons .n-button {
  min-width: 50px;
  height: 28px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.action-buttons .n-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 🎯 响应式设计 */
@media (max-width: 1200px) {
  .order-info-card {
    max-width: 240px;
  }

  .customer-info-card,
  .price-info-card,
  .time-info-card {
    font-size: 13px;
  }
}

/* 🌙 深色模式适配 */
html.dark .data-table :deep(.n-data-table-th) {
  background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
  color: #ecf0f1;
}

/* 深色模式表格行悬停效果 - 彩虹色动态渐变效果 */
html.dark .data-table :deep(.n-data-table-tr:hover .n-data-table-td) {
  background: linear-gradient(90deg,
      rgba(255, 0, 0, 0.3) 0%,
      rgba(255, 165, 0, 0.3) 12.5%,
      rgba(255, 255, 0, 0.3) 25%,
      rgba(0, 255, 0, 0.3) 37.5%,
      rgba(0, 255, 255, 0.3) 50%,
      rgba(0, 0, 255, 0.3) 62.5%,
      rgba(75, 0, 130, 0.3) 75%,
      rgba(238, 130, 238, 0.3) 87.5%,
      rgba(255, 0, 0, 0.3) 100%) !important;
  background-size: 400% 100%;
  animation: rainbowMove 4s linear infinite;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 0, 0, 0.3);
  z-index: 0;
}

html.dark .data-table :deep(.n-data-table-tr:hover .n-data-table-td)>* {
  position: relative;
  z-index: 2;
}

/* 深色模式选中行的彩虹色动态渐变效果 */
html.dark .data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td) {
  background: linear-gradient(90deg,
      rgba(255, 0, 0, 0.35) 0%,
      rgba(255, 165, 0, 0.35) 12.5%,
      rgba(255, 255, 0, 0.35) 25%,
      rgba(0, 255, 0, 0.35) 37.5%,
      rgba(0, 255, 255, 0.35) 50%,
      rgba(0, 0, 255, 0.35) 62.5%,
      rgba(75, 0, 130, 0.35) 75%,
      rgba(238, 130, 238, 0.35) 87.5%,
      rgba(255, 0, 0, 0.35) 100%) !important;
  background-size: 400% 100%;
  animation: rainbowMove 4s linear infinite;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 0, 0, 0.35);
  z-index: 0;
}

html.dark .data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td)>* {
  position: relative;
  z-index: 2;
}

html.dark .order-number {
  background: linear-gradient(135deg, #3498db, #5dade2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

html.dark .customer-avatar {
  background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
}

/* 深色模式固定列样式 */
html.dark .data-table :deep(.n-data-table-td.n-data-table-td--fixed-left),
html.dark .data-table :deep(.n-data-table-td.n-data-table-td--fixed-right) {
  position: sticky !important;
  z-index: 10 !important;
  background: var(--n-td-color) !important;
}

/* 深色模式固定列在悬浮时的背景处理 */
html.dark .data-table :deep(.n-data-table-tr:hover .n-data-table-td.n-data-table-td--fixed-left),
html.dark .data-table :deep(.n-data-table-tr:hover .n-data-table-td.n-data-table-td--fixed-right) {
  background: var(--n-td-color-hover) !important;
  z-index: 10 !important;
}

/* 深色模式固定列在选中时的背景处理 */
html.dark .data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td.n-data-table-td--fixed-left),
html.dark .data-table :deep(.n-data-table-tr.rainbow-selected-row .n-data-table-td.n-data-table-td--fixed-right) {
  background: var(--n-td-color-hover) !important;
  z-index: 10 !important;
}

/* 深色模式表格单元格文字样式 */
html.dark .data-table :deep(.n-data-table-td) {
  color: #e8eaed !important;
  font-weight: 500;
}

/* 深色模式表格行悬停样式 */
html.dark .data-table :deep(.n-data-table-tr:hover) {
  background-color: rgba(255, 255, 255, 0.05) !important;
}

/* 数字类型文字样式 */
.data-table :deep(.n-data-table-td) .unit-price,
.data-table :deep(.n-data-table-td) .total-price,
.data-table :deep(.n-data-table-td) .quantity-badge {
  font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
  font-weight: 600;
  font-variant-numeric: tabular-nums;
}

/* 订单号样式 */
.data-table :deep(.n-data-table-td) .order-number {
  font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
  font-weight: 700;
  font-size: 14px;
  letter-spacing: 0.5px;
}

/* 客户信息文字样式 */
.data-table :deep(.n-data-table-td) .customer-name,
.data-table :deep(.n-data-table-td) .product-name {
  font-weight: 600;
  font-size: 15px;
}

/* 状态标签文字样式 */
.data-table :deep(.n-data-table-td) .n-tag {
  font-weight: 600;
  font-size: 13px;
  letter-spacing: 0.2px;
}

/* 紧凑搜索表单样式 */
.compact-search-container {
  background: #f8f9fa;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 8px 8px;
}

.compact-search-form {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.compact-search-form .n-form-item {
  margin-bottom: 0 !important;
}

.compact-input {
  width: 200px;
}

.compact-select {
  width: 200px;
}

.compact-btn {
  height: 28px;
  border-radius: 6px;
  font-size: 12px;
  padding: 0 12px;
}

/* 现代化弹窗样式 */
.modern-modal {
  backdrop-filter: blur(10px);
}

.modern-modal :deep(.n-card) {
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  overflow: hidden;
}

.modal-header {
  padding: 24px 24px 16px;
  border-bottom: 1px solid #f0f0f0;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
}

.modal-title-wrapper {
  display: flex;
  align-items: center;
  gap: 16px;
}

.modal-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 8px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.modal-title-text h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #262626;
}

.modal-subtitle {
  margin: 4px 0 0;
  font-size: 14px;
  color: #666;
  opacity: 0.8;
}

.modal-content {
  padding: 24px;
  max-height: 60vh;
  overflow-y: auto;
}

.form-grid {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-section {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e8e8e8;
}

.section-title {
  margin: 0 0 16px;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title::before {
  content: '';
  width: 4px;
  height: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 2px;
}

.form-row {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.form-item {
  flex: 1;
  min-width: 200px;
}

.form-item.full-width {
  width: 100%;
}

.modern-input :deep(.n-input) {
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
  background: white;
}

.modern-input :deep(.n-input:hover) {
  border-color: #40a9ff;
  box-shadow: 0 2px 8px rgba(64, 169, 255, 0.1);
}

.modern-input :deep(.n-input:focus-within) {
  border-color: #40a9ff;
  box-shadow: 0 0 0 2px rgba(64, 169, 255, 0.2);
}

.modern-select :deep(.n-base-selection) {
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
}

.modern-select :deep(.n-base-selection:hover) {
  border-color: #40a9ff;
  box-shadow: 0 2px 8px rgba(64, 169, 255, 0.1);
}

.modern-textarea :deep(.n-input) {
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
}

.modern-textarea :deep(.n-input:hover) {
  border-color: #40a9ff;
  box-shadow: 0 2px 8px rgba(64, 169, 255, 0.1);
}

.total-amount :deep(.n-input-number) {
  background: linear-gradient(135deg, #f6ffed 0%, #f6ffed 100%);
  border: 1px solid #b7eb8f;
}

.total-amount :deep(.n-input-number .n-input) {
  background: transparent;
  font-weight: 600;
  font-size: 16px;
  color: #52c41a;
}

.modal-actions {
  padding: 16px 24px 24px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
  display: flex;
  justify-content: flex-end;
}

.cancel-btn {
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  border-color: #40a9ff;
  color: #40a9ff;
}

.confirm-btn {
  border-radius: 8px;
  background: linear-gradient(135deg, #40a9ff 0%, #1890ff 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
  transition: all 0.3s ease;
}

.confirm-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(24, 144, 255, 0.4);
}

.confirm-btn:active {
  transform: translateY(0);
}

/* 弹窗动画效果 */
.modern-modal :deep(.n-modal) {
  animation: modalFadeIn 0.3s ease-out;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: scale(0.95) translateY(-20px);
  }

  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

/* 紧凑表格头部样式 */
.compact-table-header {
  margin-bottom: 8px;
  display: flex;
  justify-content: flex-start;
  gap: 8px;
}

.compact-add-btn {
  height: 28px;
  padding: 0 12px;
  font-size: 12px;
  border-radius: 6px;
  margin-top: 10px;
  margin-left: 10px;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .compact-search-form {
    flex-direction: column;
    gap: 8px;
  }

  .compact-input,
  .compact-select {
    width: 100%;
  }

  .form-row {
    flex-direction: column;
  }

  .form-item {
    min-width: 100%;
  }

  .modern-modal :deep(.n-card) {
    margin: 16px;
    width: calc(100% - 32px) !important;
  }
}

.pagination-section {
  flex-shrink: 0;
  padding: 8px 20px;
  margin-top: 0px;
  display: flex;
  justify-content: flex-end;
  background: var(--bg-color-primary);
  border: 1px solid var(--border-color-primary);
  border-top: none;
  border-radius: 0 0 12px 12px;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 时间显示样式 */
.time-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.time-date {
  font-size: 13px;
  color: #1890ff;
  font-weight: 500;
}

.time-time {
  font-size: 12px;
  color: #666;
  font-family: Monaco, Consolas, monospace;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: var(--spacing-md);
  }

  .table-header {
    flex-direction: column;
    gap: var(--spacing-md);
    align-items: stretch;
  }
}
</style>